package milu.servlets;

import java.io.IOException;
import java.io.InputStream;

import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.fileupload.FileUploadException;
import com.google.appengine.api.datastore.Blob;

import org.apache.commons.io.IOUtils;
import com.google.appengine.api.datastore.*;

import javax.jdo.PersistenceManager;

import milu.models.*;
import milu.*;

public class AddComment extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        MyUser myUser = (MyUser)request.getAttribute("myUser");
        if(myUser == null) {
            response.sendRedirect("/"); 
            return;
        }
        String comment = request.getParameter("comment");
        String recipeKey = request.getParameter("recipeKey");
        if(comment == null || comment.equals("") || recipeKey == null || recipeKey.equals("")) {
            response.sendRedirect("/"); 
            return;
        }

		PersistenceManager pm = Datastore.getPersistenceManager();
        Key k = KeyFactory.stringToKey(recipeKey);
        try {
            RecipeComment recipeComment = new RecipeComment(k, myUser.getKey(), new Text(comment));

            pm.makePersistent(recipeComment);
        } finally {
			Datastore.finishRequest();
        }

        response.sendRedirect("/recipes/"+k.getId()+"#comments");
    }

}
